import fs from 'fs'
import path from 'path'
import express from 'express'
import router from './server-router'
import favicon from 'serve-favicon'
import logger from 'morgan'
import * as devEnv from '../build/setup-dev-env'
import config from '../server.config'
import * as $helpers from './helpers'

const app = express()

export default app

// app.use((req, res, next) => shareRoot(req.originalUrl, config.basename)(req, res, next))

const basenameList = ['/demo/xyz', '/safari/abc', '/test233', '/sth/good'].concat(config.basename)

basenameList.forEach(basename => app.use($helpers.shareRoot(basename)))

// app.use($helpers.shareRoot(config.basename))

app.engine(
  'js',
  require('express-react-views').createEngine({
    beautify: process.env.NODE_ENV === 'development',
    transformViews: false,
  })
)
app.set('views', __dirname + '/../views')
app.set('view engine', 'js')

app.use(favicon(path.join(__dirname, '../favicon.ico')))
app.use(logger('dev'))

const staticPublicPath = config.publicPath.indexOf(config.basename) === 0
  ? config.publicPath.replace(config.basename, '')
  : config.publicPath

if (process.env.NODE_ENV === 'development') {
  app.use(devEnv.setupClient(staticPublicPath))
  // 开发模式里，用 src 里的静态资源
  app.use(staticPublicPath, express.static(path.join(__dirname, '../src')))
}

app.use('/mock', (req, res, next) => {
  const {
    url: target
  } = req
  const filePath = path.join(__dirname, '../src', `${target}.json`)
  try {
    const data = fs.readFileSync(filePath, 'utf-8')
    res.type('application/json')
    res.send(data)
  } catch (error) {
    next(error)
  }
})

app.use(router)

// error handlers

// development error handler
// will print stacktrace
if ('development' === app.get('env')) {
  app.use((err, req, res, next) => {
    res.status(err.status || 500)
    const message = (err.message + '\n' + err.stack)
      .split('\n')
      .map(content => `<p style="margin: 0; padding: 0;">${content}</p>`)
      .join('')
    res.send(message)
  })
}
